from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets
from django.contrib.auth.models import User, Group
from rest_framework.decorators import api_view
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework.utils import json

from tutorial import settings
from tutorial.quickstart.config import HOST
from tutorial.quickstart.models import MovieMaoyan, ArticleList
from tutorial.quickstart.models import MovieCelebrityList
from tutorial.quickstart.models import MovieCommentList
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer, ArticleListSerializer
from tutorial.quickstart.serializers import MovieSerializer
from tutorial.quickstart.serializers import MovieCommentListSerializer
from tutorial.quickstart.serializers import MovieCelebrityListSerializer
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, StreamingHttpResponse
import mimetypes
# import settings
import os

'''
查询电影top100
需要做分页效果
param: pageSize 每页大小
param: pageNo 第多少页
'''


@csrf_exempt
def select_movie_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        body = request.body.decode("utf-8")
        if body != "":
            dic_data = json.loads(body)
            pageSize = str(dic_data['pageSize'])
            if pageSize != "" and pageSize != None:
                queryset = MovieMaoyan.objects.order_by('id')[0:int(pageSize)]
                serializer = MovieSerializer(queryset, many=True)
                return JsonResponse(serializer.data, safe=False)

        queryset = MovieMaoyan.objects.all()
        serializer = MovieSerializer(queryset, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        # 由于从MovieMaoyan.objects获取出来的是一个字典，所以定义result为字典，并设置其他参数
        result = {}
        movie_list = {}
        body = request.body.decode("utf-8")
        pageSize = '20'
        pageNo = '1'
        if body != "":
            dic_data = json.loads(body)
            # 判断是否有pageSize这个key
            if 'pageSize' in dic_data.keys():
                # pageSize: 每一页需要数据的数量
                pageSize = str(dic_data['pageSize'])
            else:
                pageSize = '20'

            # pageNo
            if 'pageNo' in dic_data.keys():
                # pageNo: 第多少页
                pageNo = str(dic_data['pageNo'])
            else:
                pageNo = '1'

            queryset = MovieMaoyan.objects.order_by('id')[
                       (int(pageNo) - 1) * int(pageSize):(int(pageNo)) * int(pageSize)]
            serializer = MovieSerializer(queryset, many=True)
            movie_list['movieList'] = serializer.data
            result['data'] = movie_list
            result['code'] = '000000'
            result['message'] = '成功'
            return JsonResponse(result, safe=False)
        else:
            # 表示获取的默认的第一页数据
            queryset = MovieMaoyan.objects.order_by('id')[0:int(pageSize)]
            serializer = MovieSerializer(queryset, many=True)
            movie_list['movieList'] = serializer.data
            result['data'] = movie_list
            result['code'] = '000000'
            result['message'] = '成功'
            return JsonResponse(result, safe=False)


# 获取电影中的演职列表信息
@csrf_exempt
def select_celebrity_list(request):
    if request.method == 'POST':
        result = {}
        celebrity_list = {}
        body = request.body.decode("utf-8")
        # print(body)
        if body != "{}":
            dic_data = json.loads(body)
            movie_id = dic_data['movieId']
            queryset = MovieCelebrityList.objects.filter(movie_id=movie_id)
            serializer = MovieCelebrityListSerializer(queryset, many=True)
            celebrity_list['celebrityList'] = serializer.data
            result['data'] = celebrity_list
            result['code'] = '000000'
            result['message'] = '成功'
        return JsonResponse(result, safe=False)


# 获取电影中的热门评论信息
@csrf_exempt
def select_comment_list(request):
    if request.method == 'POST':
        result = {}
        comment_list = {}
        body = request.body.decode("utf-8")
        # print(body)
        if body != "{}":
            dic_data = json.loads(body)
            movie_id = dic_data['movieId']
            queryset = MovieCommentList.objects.filter(movie_id=movie_id)
            serializer = MovieCommentListSerializer(queryset, many=True)
            comment_list['commentList'] = serializer.data
            result['data'] = comment_list
            result['code'] = '000000'
            result['message'] = '成功'
        return JsonResponse(result, safe=False)


def hi(request):
    return render_to_response("index.html")


def index2(request):
    return render_to_response("index2.html")


# 获取文章详情
def article_detail(request, id):
    return render_to_response("articles/article_" + str(id) + ".html")


# 获取精选文章列表中的内容
@csrf_exempt
def articles(request):
    if request.method == 'POST':
        result = {}
        article_list = {}
        body = request.body.decode("utf-8")
        pageSize = '20'
        pageNo = '1'
        if body != "":
            dic_data = json.loads(body)
            # 判断是否有pageSize这个key
            if 'pageSize' in dic_data.keys():
                # pageSize: 每一页需要数据的数量
                pageSize = str(dic_data['pageSize'])
            else:
                pageSize = '20'

            # pageNo
            if 'pageNo' in dic_data.keys():
                # pageNo: 第多少页
                pageNo = str(dic_data['pageNo'])
            else:
                pageNo = '1'

            queryset = ArticleList.objects.order_by('id')[
                       (int(pageNo) - 1) * int(pageSize):(int(pageNo)) * int(pageSize)]
            serializer = ArticleListSerializer(queryset, many=True)
            print(type(serializer.data))
            for i in range(len(serializer.data)):
                serializer.data[i]['linkAddr'] = HOST + "quickstart/articles/article_" + str(i + 1) + ".html"
            article_list['articleList'] = serializer.data
            result['data'] = article_list
            result['code'] = '000000'
            result['message'] = '成功'
            return JsonResponse(result, safe=False)
    if request.method == 'GET':
        return render_to_response("articles/article_1.html")


# 下载apk
from wsgiref.util import FileWrapper


def downloadApk(request):
    fileName = "release.apk"
    filepath = os.path.join(settings.MEDIA_ROOT, fileName)
    wrapper = FileWrapper(open(filepath, 'rb'))
    content_type = mimetypes.guess_type(filepath)[0]
    response = StreamingHttpResponse(wrapper, content_type)
    response['Content-Disposition'] = 'attachment; filename=' + fileName

    return response
